import os
import django
# 设置 Django 项目的配置
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
# 初始化 Django
django.setup()

from django.utils import timezone
from datetime import timedelta
from random import randint
from users.models import User
from management.models import UserControl
from management.tasks import UserDataTasks


def restore_user_tasks():
    # 当前时间
    current_time = timezone.now()
    # 三天前的时间
    three_days_ago = current_time - timedelta(days=3)

    # 遍历所有用户
    for user in User.objects.all():
        try:
            # 检查用户是否有 UserControl 实例
            user_control, created = UserControl.objects.get_or_create(user=user)

            # 如果 last_activity 非空且在三天内
            if user_control.last_activity and user_control.last_activity >= three_days_ago:
                # 设置 task_count 为 1
                user_control.task_count = 1

                # 生成一个 30 分钟到 6 小时之间的随机延迟
                countdown = randint(1800, 21600)

                # 递交一个定时任务
                UserDataTasks.submit_or_replace_task(user.id, UserDataTasks.async_process_user_data_cycle,
                                                     countdown=countdown)

                # 更新 next_task_time 为任务预计执行的时间
                user_control.next_task_time = current_time + timedelta(seconds=countdown)

            else:
                # 超过三天没有活动的用户，清空 task_count 并重置 next_task_time
                user_control.task_count = 0
                user_control.next_task_time = None

            if user_control.is_computing:
                user_control.is_computing = False
            # 保存更新
            user_control.save()

        except Exception as e:
            print(f"Error processing user {user.id}: {e}")


# 运行恢复脚本
restore_user_tasks()
